var mongoose = require('mongoose');
var models = require('../models');
var User = models.User;
var EventProxy = require('eventproxy');

exports.signUp = function (req, res, next) {
	var loginName = req.body.loginName,
		password = req.body.password,
		email = req.body.email;
	var ep = new EventProxy();
	
	ep.fail(next);
	ep.on('signUp_error', function (msg) {
		res.json({ result: 'fail', msg: msg });
	})

	//信息是否为空
	if (!loginName || !password || !email) {
		ep.emit('signUp_error', '信息填写不完整！');
		return;
	}

	//用户名或邮箱是否重复
	User.find({ $or: [
		{ loginName: loginName },
		{ email: email }
	] },ep.done(function (users) {
		if (users && users.length) {
			ep.emit('signUp_error', '用户名或邮箱已被注册！');
		}else{
			//保存新用户
			var user = new User();
			user.loginName = loginName;
			user.password = password;
			user.email = email;
			
			user.save(ep.done(function(){
				res.json({ result: 'success' });
			}));
		}
	}));
}

exports.login = function (req, res,next) {
	var loginName = req.body.loginName,
		password = req.body.password;
	var ep=EventProxy();
	
	ep.fail(next);
	ep.on('login_error',function(msg){
		res.json({result:'fail',msg:msg});
	});
	
	ep.on('find_user',function(user){
		if (!user) {
			return ep.emit('login_error','用户名不存在！');
		}
		if (user.password != password) {
			return ep.emit('login_error','密码不正确！');
		}
		user.lastLoginAt = new Date();
		user.save(ep.done(function () {
			req.session.user = {_id:user._id,loginName: loginName}
			console.log('login success:' + loginName);
			res.json({ result: 'success' });
		}));
	});
	if(loginName.indexOf('@')>-1)
		User.findOne({email:loginName}, ep.done('find_user'));
	else
		User.findOne({ loginName: loginName }, ep.done('find_user'));
}

exports.logOut = function (req, res) {
	req.session.user = null;
	res.redirect('/');
}